<template>
  <a-drawer
    :title="title"
    :maskClosable="true"
    width=400
    placement="right"
    :closable="true"
    @close="close"
    :visible="visible"
    v-if="visible"
    style="overflow: auto;padding-bottom: 53px;">
    <a-form>
      <a-form-item>
        <div style="background: #fff;padding-left:16px;height: 100%; margin-top: 5px">
          <a-alert type="info" :showIcon="true">
            <div slot="message">
              <span v-if="this.currSelected.title">{{ getCurrSelectedTitle() }}</span>
              <span v-else style="color:#959595">请选择</span>
              <a v-if="this.currSelected.title" style="margin-left: 10px" @click="onClearSelected">取消选择</a>
            </div>
          </a-alert>
          <a-input-search v-model="searchValue"
                          @search="onSearch"
                          @change="onChange"
                          style="width:100%;margin-top: 10px"
                          placeholder="请输入部门名称" />
          <!-- 树-->
          <a-spin :spinning='Loading'>
            <a-col class="treeHeight" :md="24" :sm="24">
              <a-tree
                multiple
                @select="onSelect"
                :selectedKeys="selectedKeys"
                :treeData="treeData"
                :checkStrictly="checkStrictly"
                :load-data="onLoadData">
                <template slot="title" slot-scope="{ title }">
                  <span v-if="searchValue && title.indexOf(searchValue) > -1">
                    <span v-for="(match, index) in matchSearchValues(title, searchValue)" :key="index">
                      <span v-if="match.isSearchValue" style="color: #f50">
                        {{ match.text }}
                      </span>
                      <span v-else>
                        {{ match.text }}
                      </span>
                    </span>
                  </span>
                  <span v-else>{{ title }}</span>
                </template>
              </a-tree>
            </a-col>
          </a-spin>
        </div>
      </a-form-item>
    </a-form>
    <div class="drawer-bootom-button">
      <a-button @click="handleSubmit(false)" style="margin-right: 0.8rem">取消选择
      </a-button>
      <a-button @click="handleSubmit(true)" type="primary" style="margin-right: 0.8rem">确认选择
      </a-button>
    </div>
  </a-drawer>
</template>
<script>
import { getDeptListByName, queryDepartTreeLazy } from '@/api/api'
import { mapGetters } from 'vuex'
import { cloneObject } from '@/utils/util'

export default {
  name: 'RoleModal',
  components: {},
  props: ['modelSelect'],
  data() {
    return {
      title: '所在机构',
      visible: false,
      hiding: true,
      treeData: [],
      treeDataSource: [],
      searchValue: '',
      allTreeKeys: [],
      selectedKeys: [],
      currSelected: {},
      checkStrictly: true,
      model: {},
      Loading: false
    }
  },
  watch: {
    visible() {
      if (this.visible) {
        this.loadTree()
      }
    }
  },
  methods: {
    ...mapGetters(['departInfo']),
    matchSearchValues(text, searchValue) {
      const regex = new RegExp(`(${searchValue})`, 'gi')
      const matches = []
      let lastIndex = 0
      text.replace(regex, (match, p1, offset) => {
        if (offset > lastIndex) {
          matches.push({ text: text.slice(lastIndex, offset), isSearchValue: false })
        }
        matches.push({ text: p1, isSearchValue: true })
        lastIndex = offset + match.length
      })
      if (lastIndex < text.length) {
        matches.push({ text: text.slice(lastIndex), isSearchValue: false })
      }
      return matches
    },
    show() {
      this.currSelected = {}
      this.selectedKeys = []
      if (this.modelSelect) {
        this.currSelected = cloneObject(this.modelSelect)
        if (this.currSelected) {
          this.selectedKeys = [this.currSelected.id]
        }
      }
      this.visible = true
    },
    loadTree() {
      this.Loading = true
      this.treeData = []
      this.treeDataSource = []
      queryDepartTreeLazy({ id: this.departInfo().parentId, isRoot: true }).then(res => {
        if (res.success) {
          let arr = [...res.result]
          this.treeData = arr
          this.treeDataSource = arr
          this.Loading = false
        }
      })
    },
    onLoadData(treeNode) {
      return new Promise(resolve => {
        if (treeNode.dataRef.children && treeNode.dataRef.children.length > 0) {
          resolve()
          return
        }
        queryDepartTreeLazy({ id: treeNode.value, isRoot: false }).then(res => {
          if (res.success) {
            treeNode.dataRef.children = [...res.result]
            this.treeData = [...this.treeData]
            resolve()
          }
        })
      })
    },
    onSearch(value) {
      this.treeData = []
      if (value) {
        this.Loading = true
        getDeptListByName({ name: value }).then(res => {
          this.Loading = false
          if (res.success) {
            for (let item of res.result) {
              if (!item.title) item.title = item.departName
              item.scopedSlots = { title: 'title' }
            }
            this.treeData = res.result
          } else {
            this.$message.warning(res.message)
          }
        })
      } else {
        this.treeData = cloneObject(this.treeDataSource)
      }
    },
    onChange(e) {
      const { value } = e.target
      if (!value) {
        this.searchValue = ''
        this.treeData = cloneObject(this.treeDataSource)
      }
    },
    handleSubmit(exit) {
      if (exit) {
        this.$emit('ok', this.currSelected)
        this.close()
      } else {
        this.onClearSelected()
        this.$emit('ok', { departName: '', id: '' })
        this.close()
      }
    },
    getCurrSelectedTitle() {
      return !this.currSelected.title ? '' : this.currSelected.title
    },
    onClearSelected() {
      this.currSelected = {}
      this.selectedKeys = []
    },
    onSelect(selectedKeys, e) {
      this.hiding = false
      let record = e.node.dataRef
      this.currSelected = Object.assign({}, record)
      this.model = this.currSelected
      this.selectedKeys = [record.key]
      this.model.parentId = record.parentId
    },
    handleClear() {
      this.selectedKeys = []
      this.visible = false
      this.searchValue = ''
      this.treeData = []
    },
    close() {
      this.handleClear()
    }
  }
}
</script>
<style lang="less" scoped>
.drawer-bootom-button {
  position: absolute;
  bottom: 0;
  width: 100%;
  border-top: 1px solid #e8e8e8;
  padding: 10px 16px;
  text-align: right;
  left: 0;
  background: #fff;
  border-radius: 0 0 2px 2px;
}

.ant-drawer {
  /deep/ .ant-drawer-body {
    padding: 10px
  }
}

.treeHeight {
  height: ~"calc(100vh - 215px)";
  overflow: auto;
}

</style>